<?php
#########################################################
#                                                       #
#  ELV_AT / DIRECT DEBIT payment method class           #
#  This module is used for real time processing of      #
#  Austrian Bankdata of customers.                      #
#                                                       #
#  Copyright (c) 2009-2010 Novalnet AG                  #
#                                                       #
#  Released under the GNU General Public License        #
#  Novalnet_elv_at module Created By Dixon Rajdaniel    #
#  This free contribution made by request.              #
#  If you have found this script usefull a small        #
#  recommendation as well as a comment on merchant form #
#  would be greatly appreciated.                        #
#                                                       #
#  Version : novalnet_elv_at.php 1.0.1 2011-06-21       #
#                                                       #
#########################################################

class novalnet_elv_at {

	var $code;
	var $title;
	var $description;
	var $enabled;
	var $proxy;
	var $callback_type;
	var $is_ajax = false;  
	var $db;
	
	function novalnet_elv_at() {
	global $order, $novalnet,$db;
		$this->code         = 'novalnet_elv_at';
		$this->title        = MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_TITLE;
		$this->public_title = MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_PUBLIC_TITLE;
		$this->description  = MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_DESCRIPTION;
		$this->sort_order   = MODULE_PAYMENT_NOVALNET_ELV_AT_SORT_ORDER;
		$this->enabled      = ((MODULE_PAYMENT_NOVALNET_ELV_AT_STATUS == 'True') ? true : false);
		$this->proxy        = MODULE_PAYMENT_NOVALNET_ELV_AT_PROXY;
		$this->db           = $db;
		$this->returnURL = (CHECKOUT_AJAX_STAT == 'true' ? FILENAME_CHECKOUT : FILENAME_CHECKOUT_PAYMENT);
		
	if($_SESSION['nn_tid_elv_at']) {
		if($_SESSION['max_time_elv_at'] && time() > $_SESSION['max_time_elv_at']) {
			unset($_SESSION['nn_tid_elv_at']);
			$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode(utf8_encode(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SESSION_ERROR));
		if ($novalnet->is_ajax)
			$_SESSION['checkout_payment_error'] = $payment_error_return;
		else
			redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));		
		}
		if( $_GET['new_novalnet_pin_elv_at'] == 'true') {
			$_SESSION['new_novalnet_pin_elv_at'] = true;
			$novalnet->secondcall();
		}
		if(!$novalnet->is_ajax && $_SESSION['email_reply_check_elv_at']=='Email Reply' && !isset($_SESSION['xml_resp_error_elv_at']))
			$novalnet->secondCall();
	}
		$this->isActivatedCallback = false;	
	if(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS != 'False')
		$this->isActivatedCallback = true;
	if ((int)MODULE_PAYMENT_NOVALNET_ELV_AT_ORDER_STATUS_ID > 0)
		$this->order_status = MODULE_PAYMENT_NOVALNET_ELV_AT_ORDER_STATUS_ID;
	if (is_object($order)) 
		$this->update_status();
	}
  
  
	function update_status() {
	global $order;
		if ( ($this->enabled == true) && ((int)MODULE_PAYMENT_NOVALNET_ELV_AT_ZONE > 0) ) {
		$check_flag = false;
		$check = $this->db->db_query("SELECT zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " WHERE geo_zone_id = '" . MODULE_PAYMENT_NOVALNET_ELV_AT_ZONE . "' and zone_country_id = '" . $order->billing['country']['id'] . "' ORDER BY zone_id");
		while (!$check->EOF) {
			if ($check->fields['zone_id'] < 1) {
				$check_flag = true;
			break;
			} elseif ($check->fields['zone_id'] == $order->billing['zone_id']) {
				$check_flag = true;
				break;
			}
			$check->MoveNext();
		}
		if ($check_flag == false) {
			$this->enabled = false;
		}
		}
	}

	function javascript_validation() {
		return false;
	}

	function selection() {
		global $order, $novalnet;
		$bank_account = $_POST['bank_account_at'];
		if(!$bank_account)
			$bank_account = $_SESSION['bank_account_at'];
			$bank_code = $_POST['bank_code_at'];
		if(!$bank_code)
			$bank_code = $_SESSION['bank_code_at'];
			$bank_account_holder_at = $_POST['bank_account_holder_at'];
		if(!$bank_account_holder_at)
			$bank_account_holder_at = $_SESSION['bank_account_holder_at'];
		if(!$bank_account_holder_at)
			$bank_account_holder_at = $order->billing['firstname'].' '.$order->billing['lastname'];
		if ($novalnet->is_ajax || (!$novalnet->is_ajax && !$_SESSION['nn_tid_elv_at'])) {
			$selection = array('id' => $this->code,
			                   'module' => $this->public_title,
			                   'fields' => array(array('title' => MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_BANK_ACCOUNT_OWNER,
			                                           'field' => draw_input_field('bank_account_holder_at', $bank_account_holder_at, 'id="'.$this->code.'-bank_account_holder_at"'),
			                                           'tag' => $this->code.'-bank_account_holder_at'),
			                                    array('title' => MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_BANK_ACCOUNT_NUMBER,
			                                           'field' => draw_input_field('bank_account_at', $_SESSION['bank_account_at'], 'id="'.$this->code.'-bank_account_at"'.$onFocus),
			                                           'tag' => $this->code.'-bank_account_at'),
			                                    array('title' => MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_BANK_CODE,
			        									'field' => draw_input_field('bank_code_at', $_SESSION['bank_code_at'], 'id="'.$this->code.'-bank_code_at"'.$onFocus),
														'tag' => $this->code.'-bank_code_at'),
						 						array('title' => '', 
						 								'field' => MODULE_PAYMENT_NOVALNET_ELV_AT_INFO)));
			$amount_check = $novalnet->findTotalAmount();
			$_SESSION['amount_first_elv_at']=$amount_check;
			if($this->isActivatedCallback && strtolower($order->customer['country']['iso_code_2']) == 'de' && $amount_check >= MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_MIN_LIMIT ) {		
				if(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS == 'Email Reply')
					$selection['fields'][] = array('title' => MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_EMAIL, 
													'field' => draw_input_field ('user_email_elv_at', $_SESSION['user_email_elv_at'], 'id="'.$this->code.'-callback" ') );
				else {
					if( MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS == 'Callback (Telefon & Handy)') 
						$selection['fields'][] = array('title' => MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS_TEL, 
														'field' => draw_input_field ('user_tel_elv_at', $_SESSION['user_tel_elv_at'], 'id="'.$this->code.'-callback" ') );
					if(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS == 'SMS (nur Handy)')  
						$selection['fields'][] = array('title' => MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS_MOB, 
														'field' => draw_input_field ( 'user_tel_elv_at', $_SESSION['user_tel_elv_at'], 'id="'.$this->code.'-callback" '));
				}
			}
		}
		$amount_check = $_SESSION['amount_first_elv_at'];
		if($this->isActivatedCallback && strtolower($order->customer['country']['iso_code_2']) == 'de' && $amount_check >= MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_MIN_LIMIT ) {
			if ($novalnet->is_ajax || (!$novalnet->is_ajax && $_SESSION['nn_tid_elv_at'])) {
				if(!$novalnet->is_ajax)
					$selection = array('id' => $this->code, 'module' => $this->public_title);
				if(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS == 'Email Reply') { 	
					if ($novalnet->is_ajax) {
						$selection['fields'][] = array('title' => '','field' => MODULE_PAYMENT_NOVALNET_ELV_AT_EMAIL_INFO_DESC);
						$selection['fields'][] = array('title' => '', 'field' => draw_checkbox_field('email_replied_elv_at', '1', false).MODULE_PAYMENT_NOVALNET_ELV_AT_EMAIL_REPLY_INFO);
					} else
						$selection['fields'][] = array('title' => MODULE_PAYMENT_NOVALNET_ELV_AT_EMAIL_INPUT_REQUEST_DESC);
				} else {
					if ($novalnet->is_ajax) {
						unset($_SESSION['email_reply_check_elv_at']);
						if( MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS == 'Callback (Telefon & Handy)')
							$selection['fields'][] = array('title' => '',
															'field' =>  MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS_TEL_NUMBER);
						if(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS == 'SMS (nur Handy)')  
							$selection['fields'][] = array('title' => '',
															'field' =>  MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS_MOB_NUMBER);
						$selection['fields'][] = array('title' => '',
														'field' =>  MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_INFO_DESC);
						$selection['fields'][] = array('title' => MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_INPUT_REQUEST_DESC, 
														'field' => draw_input_field('novalnet_pin_elv_at', '', 'id="'.$this->code.'-callback" '.$onFocus.' maxlength="4" size="4" ') );
						$selection['fields'][] = array('title' => '', 
														'field' => draw_checkbox_field('forgot_pin_elv_at', '1', false, 'id="'.$this->code.'-forgotpin"'.$onFocus).MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS_NEW_PIN);
						$selection['fields'][] = array('title' => '', 
														'field' => MODULE_PAYMENT_NOVALNET_ELV_AT_FORGOT_PIN_DIV);
					} else {
						
						$selection['fields'][] = array('title' => MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_INPUT_REQUEST_DESC, 
														'field' => draw_input_field('novalnet_pin_elv_at', '', 'id="'.$this->code.'-callback" '.$onFocus.' maxlength="4" size="4" ') );
						$selection['fields'][] = array('title' => '<a href="'.href_link($novalnet, 'new_novalnet_pin_elv_at=true', 'SSL').'">'.MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS_NEW_PIN.'</a>') ;
					}
				}
			}
		}
		if(function_exists(get_percent))
			$selection['module_cost'] = $GLOBALS['ot_payment']->get_percent($this->code);
		return $selection;
	}

	function pre_confirmation_check($vars = '') {
		global $order, $novalnet;
		if(is_array($vars) && !empty($vars))
			$data_arr = $vars;
		else
			$data_arr = $_POST;

		$_POST['bank_account_holder_at'] = trim($data_arr['bank_account_holder_at']);
		$_POST['bank_account_at'] = trim($data_arr['bank_account_at']);
		$_POST['bank_code_at'] = trim($data_arr['bank_code_at']);
		if(isset($data_arr['user_tel_elv_at']))
			$data_arr['user_tel_elv_at'] = trim($data_arr['user_tel_elv_at']);
		if(isset($data_arr['user_email_elv_at']))
			$data_arr['user_email_elv_at'] = trim($data_arr['user_email_elv_at']);
		if(isset($data_arr['novalnet_pin_elv_at']))
			$data_arr['novalnet_pin_elv_at'] = trim($data_arr['novalnet_pin_elv_at']);
		if($_SESSION['nn_tid_elv_at']) {
			if($novalnet->is_ajax && $data_arr['forgot_pin_elv_at'] && !$data_arr['novalnet_pin_elv_at']) {
				$_SESSION['new_novalnet_pin_elv_at'] = true;
				$this->secondCall();
				return;
			}
		if($novalnet->is_ajax && MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS == 'Email Reply' ) {
			if($novalnet->is_ajax && !$data_arr['email_replied_elv_at']) {
			$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode(utf8_encode(MODULE_PAYMENT_NOVALNET_ELV_AT_EMAIL_REPLY_CHECKBOX_INFO));
			if ($novalnet->is_ajax)
				$_SESSION['checkout_payment_error'] = $payment_error_return;
			else
				redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}
			else
				$_SESSION['email_reply_check_elv_at']='Email Reply';
			}
			if(isset($data_arr['novalnet_pin_elv_at']) && isset($_SESSION['nn_tid_elv_at'])) { 
				if(!is_numeric($data_arr['novalnet_pin_elv_at']) || strlen($data_arr['novalnet_pin_elv_at'] ) != 4 ) {	
					$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode(utf8_encode(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS_PIN_NOTVALID));
					if ($novalnet->is_ajax)
							$_SESSION['checkout_payment_error'] = $payment_error_return;
					else
						redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
				} else {
					if($data_arr['novalnet_pin_elv_at'] )
						$_SESSION['novalnet_pin_elv_at'] = $data_arr['novalnet_pin_elv_at'];
				}
			}
			return;
			
		} else {
			
			$error = '';
			if ($novalnet->is_ajax || (!$novalnet->is_ajax && !isset($_SESSION['nn_tid_elv_at']))) {
				if (defined('MODULE_PAYMENT_NOVALNET_ELV_AT_MANUAL_CHECK_LIMIT') AND MODULE_PAYMENT_NOVALNET_ELV_AT_MANUAL_CHECK_LIMIT)
					if ((!defined('MODULE_PAYMENT_NOVALNET_ELV_AT_PRODUCT_ID2') OR !MODULE_PAYMENT_NOVALNET_ELV_AT_PRODUCT_ID2 or preg_match('/[^\d]/', MODULE_PAYMENT_NOVALNET_ELV_AT_PRODUCT_ID2)) or (!defined('MODULE_PAYMENT_NOVALNET_ELV_AT_TARIFF_ID2') or !MODULE_PAYMENT_NOVALNET_ELV_AT_TARIFF_ID2 or preg_match('/[^\d]/', MODULE_PAYMENT_NOVALNET_ELV_AT_TARIFF_ID2)))
						$error = 'Product-ID2 and/or Tariff-ID2 missing';

				
				if(!MODULE_PAYMENT_NOVALNET_ELV_AT_VENDOR_ID || !MODULE_PAYMENT_NOVALNET_ELV_AT_AUTH_CODE || !MODULE_PAYMENT_NOVALNET_ELV_AT_PRODUCT_ID || !MODULE_PAYMENT_NOVALNET_ELV_AT_TARIFF_ID)
					$error = MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_JS_NN_MISSING;
				elseif(!$data_arr['bank_account_holder_at'] || strlen($data_arr['bank_account_holder_at'])<MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_BANK_ACCOUNT_OWNER_LENGTH) $error = MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_JS_BANK_ACCOUNT_OWNER;
				elseif(!$data_arr['bank_account_at'] || strlen($data_arr['bank_account_at'])<MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_BANK_ACCOUNT_NUMBER_LENGTH) $error = MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_JS_BANK_ACCOUNT_NUMBER;
				elseif(!$data_arr['bank_code_at'] || strlen($data_arr['bank_code_at'])<MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_BANK_CODE_LENGTH) $error = MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_JS_BANK_CODE;
		
				$_SESSION['bank_account_holder_at'] = $data_arr['bank_account_holder_at'];
				$_SESSION['bank_code_at'] = $data_arr['bank_code_at'];
				$_SESSION['bank_account_at'] = $data_arr['bank_account_at'];
				
				if (isset($data_arr['user_tel_elv_at']))
					$_SESSION['user_tel_elv_at'] = $data_arr['user_tel_elv_at'];
					
				if (isset($data_arr['user_email_elv_at']))
					$_SESSION['user_email_elv_at'] = $data_arr['user_email_elv_at'];
				
				// Callback stuff....
				//$amount_check = $this->findTotalAmount();
				//echo $_SESSION['amount_first_elv_at']; exit;
				$amount_check = $_SESSION['amount_first_elv_at'];
				
				if($this->isActivatedCallback && strtolower($order->customer['country']['iso_code_2']) == 'de' && $amount_check >= MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_MIN_LIMIT){
					if($error=='') {
						//checking email address
						if (isset($data_arr['user_email_elv_at']))
							if (!preg_match("#^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})#", $data_arr['user_email_elv_at'])){ 
								$error .= utf8_decode(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_EMAIL_NOTVALID);

						
						//checking telephone number
						if (isset($data_arr['user_tel_elv_at']))
							if( strlen( $data_arr['user_tel_elv_at']) < 8 || !is_numeric( $_POST['user_tel_elv_at']))
								$error .= utf8_decode(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS_TEL_NOTVALID);

					}
					}
					if($error!='') {
						$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode(utf8_encode($error));
						if ($novalnet->is_ajax)
							$_SESSION['checkout_payment_error'] = $payment_error_return;
						else
							redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));

					} else {
						$this->before_process($data_arr);
						if (!$novalnet->is_ajax) {
							redirect(href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false)); 		
						}
					}
					}
				}
			}
		
		if($error!='') {
		$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode($error);
		if ($this->is_ajax) {
		$_SESSION['checkout_payment_error'] = $payment_error_return;
		} else {
		redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
		}
		}
}
	function confirmation() {
	    global $order;
	
	    if($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1)
	      $total = $order->info['total'] + $order->info['tax'];
	    else
	      $total = $order->info['total'];

		//$amount_check = $this->findTotalAmount();
		$_SESSION['amount_first_elv_at']=sprintf('%.2f', $total);
		
	    $_SESSION['nn_total_elv_at'] = sprintf('%.2f', $total);
		
		$cardnoLength = strlen(str_replace(' ','',$_POST['bank_account_at']));
		$cardnoInfo = '';
		for($i=0;$i<$cardnoLength;$i++){
			$cardnoInfo .= '*';
		}
		$cardnoLength = strlen(str_replace(' ','',$_POST['bank_account_at']));
		$crdNo = str_replace(' ','',$_POST['bank_account_at']);
		$cardnoInfo = '';
		$chkLength = $cardnoLength-3;
		for($i=0;$i<$cardnoLength;$i++){
			if($i >= $chkLength){
				$cardnoInfo .= '*';
			}else{
				$cardnoInfo .= $crdNo[$i];
			}
		}
		$codeLength = strlen(str_replace(' ','',$_POST['bank_code_at']));
		$codeNo = str_replace(' ','',$_POST['bank_code_at']);
		$codeInfo = '';
		$chkLength = $codeLength-3;
		for($i=0;$i<$codeLength;$i++){
			if($i >= $chkLength)
				$codeInfo .= '*';
			else
				$codeInfo .= $codeNo[$i];
		}	
		
	    $confirmation = array('fields' => array(array('title' => MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_BANK_ACCOUNT_OWNER,
	                          'field' => $_POST['bank_account_holder_at']),
	                    array('title' => MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_BANK_ACCOUNT_NUMBER,
	                          'field' => $cardnoInfo),
	                    array('title' => MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_BANK_CODE,
				   				'field' => $codeInfo)));
		return $confirmation;
  	}

	function process_button() {
		$process_button_string = draw_hidden_field('bank_account_holder_at', $_POST['bank_account_holder_at']) .
		                         draw_hidden_field('bank_account_at', $_POST['bank_account_at']) .
		                         draw_hidden_field('bank_code_at', $_POST['bank_code_at']); 
		
		return $process_button_string;
	}

	function before_process($vars ='') {
	    global $novalnet,$order, $currencies, $customer_id,$novalnet;
	    if(is_array($vars) && !empty($vars)) {
			$data_arr = $vars;
			$is_ajax = true;
		} else
			$data_arr = $_POST;
	    if($_SESSION['nn_tid_elv_at'] && $this->isActivatedCallback) {
			if(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS == 'Email Reply')
				$_SESSION['email_reply_check_elv_at']='Email Reply';
			else
				unset($_SESSION['email_reply_check_elv_at']);
			if($novalnet->is_ajax && $data_arr['forgot_pin_elv_at'] && !$data_arr['novalnet_pin_elv_at'])
				$_SESSION['new_novalnet_pin_elv_at']=true;
			else
				$_SESSION['new_novalnet_pin_elv_at']=false;
			$aryResponse = $this->secondCall();
			if($aryResponse){
				$old_comments = $order->info['comments'];
				$order->info['comments'] = "";
				$test_mode = (strtolower(MODULE_PAYMENT_NOVALNET_ELV_AT_TEST_MODE) == 'true' or MODULE_PAYMENT_NOVALNET_ELV_AT_TEST_MODE == '1')? 1: 0;
				if($test_mode)
					$order->info['comments'] .= MODULE_PAYMENT_NOVALNET_ELV_AT_TEST_ORDER_MESSAGE;

				$order->info['comments'] .= MODULE_PAYMENT_NOVALNET_ELV_AT_TID_MESSAGE.$aryResponse['tid'];	
			}
			return;
		}
		$customer = $this->db->db_query("SELECT customers_gender, customers_dob, customers_fax FROM ". TABLE_CUSTOMERS." WHERE customers_id='". (int)$customer_id ."'");
		if(isset($customer->fields['customers_dob']))
		{
			$customers_dob = $customer->fields['customers_dob'];
		}
		else
		{ 
			$customers_dob = '';
		}
		if(isset($customer->fields['customers_fax'])){
		$customers_fax = $customer->fields['customers_fax'];
		}
		else {
		$customers_fax = '';
		}
	    $url = 'https://payport.novalnet.de/paygate.jsp';	
	    $amount = $_SESSION['amount_first_elv_at'];
	    $product_id         = MODULE_PAYMENT_NOVALNET_ELV_AT_PRODUCT_ID;
	    $tariff_id          = MODULE_PAYMENT_NOVALNET_ELV_AT_TARIFF_ID;
	    $manual_check_limit = trim(MODULE_PAYMENT_NOVALNET_ELV_AT_MANUAL_CHECK_LIMIT);
	    $manual_check_limit = str_replace(',', '', $manual_check_limit);
	    $manual_check_limit = str_replace('.', '', $manual_check_limit);
		if($manual_check_limit && $amount>=$manual_check_limit) {
	    	$product_id = MODULE_PAYMENT_NOVALNET_ELV_AT_PRODUCT_ID2;
	    	$tariff_id  = MODULE_PAYMENT_NOVALNET_ELV_AT_TARIFF_ID2;
	    }
		if($_SESSION['user_tel_elv_at'])
			$user_telephone = $_SESSION['user_tel_elv_at'];
		else
			$user_telephone	= $order->customer['telephone'];
		if($_SESSION['user_email_elv_at'])
			$user_email = $_SESSION['user_email_elv_at'];
		else
			$user_email	= $order->customer['email_address'];
		if($this->isActivatedCallback && strtolower($order->customer['country']['iso_code_2']) == 'de' && $amount >= MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_MIN_LIMIT) {
			if(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS == 'Callback (Telefon & Handy)') { 
				$this->callback_type = '&pin_by_callback=1'; 
				$url_telephone = '&tel='.$user_telephone;
			}
			if(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS == 'SMS (nur Handy)') { 
				$this->callback_type = '&pin_by_sms=1'; 
				$url_telephone = '&mobile='.$user_telephone;
			}
			if(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS == 'Email Reply') { 
				$this->callback_type = '&reply_email_check=1'; 
			}
		}
	    $user_ip = $novalnet->getRealIpAddr();
	    $urlparam = 'vendor='.MODULE_PAYMENT_NOVALNET_ELV_AT_VENDOR_ID.'&product='.$product_id.'&key=8&tariff='.$tariff_id;
	    $urlparam .= '&auth_code='.MODULE_PAYMENT_NOVALNET_ELV_AT_AUTH_CODE.'&currency='.$order->info['currency'];
	    $urlparam .= '&amount='.$amount.'&bank_account_holder='.$novalnet->html_to_utf8($_SESSION['bank_account_holder_at']).'&bank_account='.$_SESSION['bank_account_at'];
	    $urlparam .= '&bank_code='.$_SESSION['bank_code_at'].'&first_name='.$novalnet->html_to_utf8($order->customer['firstname']).'&last_name='.$novalnet->html_to_utf8($order->customer['lastname']);
	    $urlparam .= '&street='.$novalnet->html_to_utf8($order->customer['street_address']).'&city='.$novalnet->html_to_utf8($order->customer['city']).'&zip='.$order->customer['postcode'];
	    $urlparam .= '&country='.$order->customer['country']['iso_code_2'].'&email='.$user_email;
	    $urlparam .= '&search_in_street=1'.$url_telephone.'&remote_ip='.$user_ip;
	    $urlparam .= '&gender=U&birth_date='.$customers_dob.'&fax='.$customers_fax;
	    $urlparam .= '&language='.MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_LANG;
	    $test_mode = (strtolower(MODULE_PAYMENT_NOVALNET_ELV_AT_TEST_MODE) == 'true' OR MODULE_PAYMENT_NOVALNET_ELV_AT_TEST_MODE == '1')? 1: 0;
	    $urlparam .= '&test_mode='.$test_mode;
		$urlparam .= $this->callback_type;
		list($errno, $errmsg, $data) = $novalnet->perform_https_request($url, $urlparam);
		if ($errno or $errmsg) {
		      $order->info['comments'] .= '. func perform_https_request returned Errorno : '.$errno.', Error Message : '.$errmsg;
		      $payment_error_return = 'payment_error='.$this->code.'&error=' .utf8_encode($errmsg). '('.$errno.')';
		      if ($novalnet->is_ajax)
					$_SESSION['checkout_payment_error'] = $payment_error_return;
			  else
					redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL'));
	    }
		parse_str($data, $aryResponse);
		if($aryResponse['status']==100) {
			if($this->isActivatedCallback && strtolower($order->customer['country']['iso_code_2']) == 'de' && $amount >= MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_MIN_LIMIT ){			
				$_SESSION['nn_tid_elv_at'] = $aryResponse['tid'];
				$_SESSION['max_time_elv_at'] = time() + (30 * 60);
				$test_mode = (strtolower(MODULE_PAYMENT_NOVALNET_ELV_AT_TEST_MODE) == 'true' or MODULE_PAYMENT_NOVALNET_ELV_AT_TEST_MODE == '1')? 1: 0;
				if($test_mode)
					$_SESSION['test_mode_elv_at'] = $test_mode;	
				if ($novalnet->is_ajax) {
					if(MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS == 'Email Reply') {
						$checkoutmsg =MODULE_PAYMENT_NOVALNET_ELV_AT_EMAIL_REPLY_CHECK_MSG;
						$payment_error_return     = 'payment_error='.$this->code.'&error='.utf8_encode($checkoutmsg);
						$_SESSION['checkout_payment_error'] = $payment_error_return;
					} else {
						$checkoutmsg =MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_CHECK_MSG;
						$payment_error_return     = 'payment_error='.$this->code.'&error='.utf8_encode($checkoutmsg);
						$_SESSION['checkout_payment_error'] = $payment_error_return;
					}
				}
			} else {
				$test_mode = (strtolower(MODULE_PAYMENT_NOVALNET_ELV_AT_TEST_MODE) == 'true' or MODULE_PAYMENT_NOVALNET_ELV_AT_TEST_MODE == '1')? 1: 0;
				if($test_mode)
					$order->info['comments'] .= MODULE_PAYMENT_NOVALNET_ELV_AT_TEST_ORDER_MESSAGE;
					
				$order->info['comments'] .= MODULE_PAYMENT_NOVALNET_ELV_AT_TID_MESSAGE.$aryResponse['tid'];	
			}
		} else {
	      	$order->info['comments'] .= '. Novalnet Error Code : '.$aryResponse['status'].', Novalnet Error Message : '.$aryResponse['status_desc'];
	      	$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode(utf8_encode($aryResponse['status_desc']));
			redirect(href_link($novalnet->returnURL, $payment_error_return, 'SSL', true, false));
			}
		return;
  	}
  	
	function after_process() {
		global $order, $customer_id, $insert_id, $novalnet;
		if ($this->order_status)
		$this->db->db_query("UPDATE ".TABLE_ORDERS." SET orders_status='".$this->order_status."' WHERE orders_id='".$insert_id."'");
		$product_id = MODULE_PAYMENT_NOVALNET_ELV_AT_PRODUCT_ID;
		$tariff_id = MODULE_PAYMENT_NOVALNET_ELV_AT_TARIFF_ID;
		$url = 'https://payport.novalnet.de/paygate.jsp';
		$urlparam = 'vendor='.MODULE_PAYMENT_NOVALNET_ELV_AT_VENDOR_ID.'&product='.$product_id.'&key=8&tariff='.$tariff_id;
		$urlparam .= '&order_no='.$insert_id;
		$urlparam .= '&auth_code='.MODULE_PAYMENT_NOVALNET_ELV_AT_AUTH_CODE.'&status=100&tid='.$_SESSION['nn_tid_elv_at'].'&reference=BNR-'.$insert_id.'&vwz3='.$insert_id.'&vwz3_prefix='.MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_ORDERNO.'&vwz4='.date('Y.m.d').'&vwz4_prefix='.MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_ORDERDATE;
		list($errno, $errmsg, $data) = $novalnet->perform_https_request($url, $urlparam);
		unset($_SESSION['nn_tid_elv_at']);
		unset($_SESSION['bank_account_at']);
		unset($_SESSION['bank_code_at']);
		unset($_SESSION['bank_account_holder_at']);
		unset($_SESSION['max_time_elv_at']);
		unset($_SESSION['test_mode_elv_at']);
		unset($_SESSION['email_reply_check_elv_at']);
		unset($_SESSION['xml_resp_error_elv_at']);
		unset($_SESSION['user_tel_elv_at']);
		unset($_SESSION['user_email_elv_at']);
		unset($_SESSION['amount_first_elv_at']);
		return false;
	}

	function get_error() {
		$error = array('title' => MODULE_PAYMENT_NOVALNET_ELV_AT_TEXT_ERROR,
		               'error' => stripslashes(urldecode($_GET['error'])));
		return $error;
	}

	function check() {
		if (!isset($this->_check)) {
			$check = $this->db->db_query("select configuration_value from ".TABLE_CONFIGURATION." where configuration_key = 'MODULE_PAYMENT_NOVALNET_ELV_AT_STATUS'");
			$this->_check = $check->_numOfRows;
		}
		return $this->_check;
	}

	function install() {
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_ALLOWED', '', '6', '0', now())");
		$this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS', 'False', '6', '3', 'cfg_select_option(array( \'False\', \'Callback (Telefon & Handy)\', \'SMS (nur Handy)\', \'Email Reply\'), ', now())");
		$this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_MIN_LIMIT', '', '6', '2', now())");	
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_STATUS', 'True', '6', '1', 'cfg_select_option(array(\'True\', \'False\'), ', now())");
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_TEST_MODE', 'True', '6', '2', 'cfg_select_option(array(\'True\', \'False\'), ', now())");
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_VENDOR_ID', '', '6', '3', now())");
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_AUTH_CODE', '', '6', '4', now())");
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_PRODUCT_ID', '', '6', '5', now())");
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_TARIFF_ID', '', '6', '6', now())");
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_MANUAL_CHECK_LIMIT', '', '6', '7', now())");
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_PRODUCT_ID2', '', '6', '8', now())");
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_TARIFF_ID2', '', '6', '9', now())");
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_INFO', '', '6', '10', now())");
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_SORT_ORDER', '0', '6', '11', now())");
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, use_function, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_ORDER_STATUS_ID', '0', '6', '12', 'cfg_pull_down_order_statuses(', 'get_order_status_name', now())");
	    $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, use_function, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_ZONE', '0', '6', '13', 'get_zone_class_title', 'cfg_pull_down_zone_classes(', now())");
	     $this->db->db_query("insert into ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_AT_PROXY', '', '6', '14', now())");
	}

  	function remove() {
  		global $db;
    	$db->db_query("DELETE FROM ".TABLE_CONFIGURATION." WHERE configuration_key IN ('".implode("', '", $this->keys())."')");
	}

	function keys() {
		return array('MODULE_PAYMENT_NOVALNET_ELV_AT_ALLOWED', 'MODULE_PAYMENT_NOVALNET_ELV_AT_STATUS', 'MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_SMS','MODULE_PAYMENT_NOVALNET_ELV_AT_PIN_BY_CALLBACK_MIN_LIMIT','MODULE_PAYMENT_NOVALNET_ELV_AT_TEST_MODE', 'MODULE_PAYMENT_NOVALNET_ELV_AT_VENDOR_ID', 'MODULE_PAYMENT_NOVALNET_ELV_AT_AUTH_CODE', 'MODULE_PAYMENT_NOVALNET_ELV_AT_PRODUCT_ID', 'MODULE_PAYMENT_NOVALNET_ELV_AT_TARIFF_ID', 'MODULE_PAYMENT_NOVALNET_ELV_AT_MANUAL_CHECK_LIMIT', 'MODULE_PAYMENT_NOVALNET_ELV_AT_PRODUCT_ID2', 'MODULE_PAYMENT_NOVALNET_ELV_AT_TARIFF_ID2', 'MODULE_PAYMENT_NOVALNET_ELV_AT_INFO', 'MODULE_PAYMENT_NOVALNET_ELV_AT_SORT_ORDER', 'MODULE_PAYMENT_NOVALNET_ELV_AT_ORDER_STATUS_ID', 'MODULE_PAYMENT_NOVALNET_ELV_AT_ZONE', 'MODULE_PAYMENT_NOVALNET_ELV_AT_PROXY');
	}
		function secondCall()
	{
		// If customer forgets PIN, send a new PIN
		if( $_SESSION['new_novalnet_pin_elv_at'] )
			$request_type = 'TRANSMIT_PIN_AGAIN';
		else
	        $request_type = 'PIN_STATUS';

		if($_SESSION['email_reply_check_elv_at']=='Email Reply') 
			 $request_type = 'REPLY_EMAIL_STATUS';
			 
		if( $_SESSION['new_novalnet_pin_elv_at'] )
			$_SESSION['new_novalnet_pin_elv_at'] = false;
			
		
		if($request_type == 'REPLY_EMAIL_STATUS') {
			$xml = '<?xml version="1.0" encoding="UTF-8"?>
				<nnxml>                               
		  			<info_request>
			    		<vendor_id>'.MODULE_PAYMENT_NOVALNET_ELV_AT_VENDOR_ID.'</vendor_id>
			    		<vendor_authcode>'.MODULE_PAYMENT_NOVALNET_ELV_AT_AUTH_CODE.'</vendor_authcode>
			    		<request_type>'.$request_type.'</request_type>
			    		<tid>'.$_SESSION['nn_tid_elv_at'].'</tid>
		  			</info_request>
				</nnxml>'; 	
		}
		else {
			$xml = '<?xml version="1.0" encoding="UTF-8"?>
				<nnxml>                               
		  			<info_request>
			    		<vendor_id>'.MODULE_PAYMENT_NOVALNET_ELV_AT_VENDOR_ID.'</vendor_id>
			    		<vendor_authcode>'.MODULE_PAYMENT_NOVALNET_ELV_AT_AUTH_CODE.'</vendor_authcode>
			    		<request_type>'.$request_type.'</request_type>
			    		<tid>'.$_SESSION['nn_tid_elv_at'].'</tid>
			    		<pin>'.$_SESSION['novalnet_pin_elv_at'].'</pin>
		  			</info_request>
				</nnxml>'; 	

		}
		$xml_response = $this->curl_xml_post( $xml );	
				
		// Parse XML Response to object
		$xml_response = simplexml_load_string( $xml_response );
		if( $xml_response->status != 100 )		
		{
			$_SESSION['xml_resp_error_elv_at']=$xml_response->status_message;
			$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode( utf8_decode( $_SESSION['xml_resp_error_elv_at'] ) );
			if ($this->is_ajax) {
				$_SESSION['checkout_payment_error'] = $payment_error_return;
				if($request_type == 'PIN_STATUS' || $request_type == 'REPLY_EMAIL_STATUS') {
					xtc_redirect(xtc_href_link(FILENAME_CHECKOUT, $payment_error_return, 'SSL', true, false));
				}
			} else {
				xtc_redirect(xtc_href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}
		}
		else
		{	
			$array = (array) $xml_response;
			// add tid, because it's missing in the response
			$array['tid'] = $_SESSION['nn_tid_elv_at'];
			$array['statusdesc'] = $array['status_message']; // Param-name is changed
			$array['test_mode'] = $_SESSION['test_mode_elv_at'];			
			return $array;			
		}						 	
	}
	
	public function curl_xml_post( $request )
	{
	    $ch = curl_init( "https://payport.novalnet.de/nn_infoport.xml" );
	    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));
		curl_setopt($ch, CURLOPT_POST, 1);  // a non-zero parameter tells the library to do a regular HTTP post.
		curl_setopt($ch, CURLOPT_POSTFIELDS, $request);  // add POST fields
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);  // don't allow redirects
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // decomment it if you want to have effective ssl checking
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // decomment it if you want to have effective ssl checking
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  // return into a variable
		curl_setopt($ch, CURLOPT_TIMEOUT, 240);  // maximum time, in seconds, that you'll allow the CURL functions to take		  
		
		## establish connection
		$xml_response = curl_exec($ch);
		
		## determine if there were some problems on cURL execution
		$errno = curl_errno($ch);
		$errmsg = curl_error($ch);
		
		###bug fix for PHP 4.1.0/4.1.2 (curl_errno() returns high negative value in case of successful termination)
		if($errno < 0) $errno = 0;
		##bug fix for PHP 4.1.0/4.1.2
		
		if($debug)
		{
			print_r(curl_getinfo($ch));
			echo "\n<BR><BR>\n\n\nperform_https_request: cURL error number:" . $errno . "\n<BR>\n\n";
			echo "\n\n\nperform_https_request: cURL error:" . $errmsg . "\n<BR>\n\n";
		}
		
		#close connection
		curl_close($ch);
		
		return $xml_response;
	}
}
/*
order of functions:
selection              -> $order-info['total'] wrong, cause shipping_cost is net
pre_confirmation_check -> $order-info['total'] wrong, cause shipping_cost is net
confirmation           -> $order-info['total'] right, cause shipping_cost is gross
process_button         -> $order-info['total'] right, cause shipping_cost is gross
before_process         -> $order-info['total'] wrong, cause shipping_cost is net
after_process          -> $order-info['total'] right, cause shipping_cost is gross
*/
?>